package com.guimin.common.interceptor;

import com.guimin.common.util.SpringContextUtils;
import com.guimin.user.constant.UserConstant;
import com.guimin.user.dto.LoginInfoDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.regex.Pattern;

/**
 * 登录拦截器
 *
 * @author hzy
 */
@Configuration
@Slf4j
public class MyInterceptor extends HandlerInterceptorAdapter {
    /**
     * redis服务
     */
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws IOException {
        //登录认证
        if (redisTemplate == null) {
            redisTemplate = (RedisTemplate<String, Object>) SpringContextUtils.getBean("redisTemplate");
        }
        String token = request.getHeader("token");
        if (token == null || token.isEmpty() || token.length() > 200) {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;content-type=utf-8");
            response.getWriter().print("{\"success\":false,\"message\":\"用户未登录\"}");
            return false;
        }
        Object loginUser = redisTemplate.opsForValue().get("token" + token);
        if (loginUser == null) {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;content-type=utf-8");
            response.getWriter().print("{\"code\":666," +
                    "\"success\":false," +
                    "\"message\":\"用户未登录或登录已失效\"" +
                    "}");
            return false;
        }
        //授权

        return true;
    }
}
